'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	
	// 后端请求获取openId
	const appid = 'wxd74459b350a31c33';
	const secret = 'bbfcdebfcc120e81a1f9e6b720c1d4ba';
	const weChat = 'https://api.weixin.qq.com/sns/jscode2session'
	const apiUrl = weChat+'?appid='+appid+'&secret='+secret+'&js_code='+event.code+'&grant_type=authorization_code';
	const wxRes = await uniCloud.httpclient.request(apiUrl, {
		method: 'GET',
		data: {},
		contentType: 'json', // 指定以application/json发送data内的数据
		dataType: 'json' // 指定返回值为json格式，自动进行parse
	})
	
	// 判断微信服务端
	if (wxRes.status !== 200) {
		return { data: {}, code: 400, msg: `微信小程序错误` }
	} else {
		// 查询用户openId是否存在
		const res_users = await db.collection('rx-users').where({wechatId:wxRes.data.openid}).get()
		// 用户存在openId
		if (res_users.data.length > 0) {
			const res_users_clinic = await db.collection('rx-users-clinic').where({
				userId:res_users.data[0]._id, types: event.types
			}).get()
			// 判断是否存在指定类型
			if (res_users_clinic.data.length > 0) {
				if (res_users_clinic.data[0].clinic.length > 0) {
					//返回数据给客户端 1扫码0免扫码
					return { data: { userId: res_users.data[0]._id, qrcode: 0, name: res_users.data[0].name, mobile: res_users.data[0].mobile }, code: 200, msg: 'ok.' }
				}
			} else {
				await db.collection('rx-users-clinic').add({
					userId: res_users.data[0]._id, types: event.types, clinic: []
				})
			}
			//返回数据给客户端 1扫码0免扫码
			return { data: { userId: res_users.data[0]._id, qrcode: 1, name: res_users.data[0].name, mobile: res_users.data[0].mobile }, code: 200, msg: 'ok.' }
			
		// 不用户存在openId时创建用户并返回需要扫码的qrcide=1
		} else {
			const res_users = await db.collection('rx-users').add({ "wechatId": wxRes.data.openid, "self": [], name: '', mobile: '' })	// self关联的人名字
			await db.collection('rx-users-clinic').add({ userId: res_users.id, types: event.types, clinic: [] })
			//返回数据给客户端 1扫码0免扫码
			return { data: { userId: res_users.id, qrcode: 1, name: '', mobile: '' }, code: 200, msg: 'ok.' }
		}
			
		
	}
};
